﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CjcAwesomiumWrapper;
using System.Windows.Media;

namespace Cjc.ChromiumBrowser
{
	public class WebBrowserManager : IDisposable
	{
		private WebCore webCore;
		private bool disposed = false;

		public WebBrowserManager()
			: this( "" )
		{
		}

		public WebBrowserManager( string cookiePath )
			: this( cookiePath, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/531.3 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/531.3" )
//			: this( cookiePath, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5" )
		{
		}

		public WebBrowserManager( string cookiePath, string userAgentOverride )
			: this( "", cookiePath, "", "", true, userAgentOverride )
		{
		}

		public WebBrowserManager( string cachePath, string cookiePath, string pluginPath, string logPath,
			bool enablePlugins, string userAgentOverride )
		{
			webCore = new WebCore( cachePath, cookiePath, pluginPath, logPath, enablePlugins, userAgentOverride );

			CompositionTarget.Rendering += OnUpdate;
			System.Windows.Application.Current.Exit += delegate { Dispose(); };
		}

		private void OnUpdate( object sender, EventArgs e )
		{
			webCore.Update();
		}

		internal WebView CreateWebView( int width, int height, bool isTransparent, bool enableAsyncRendering, int maxAsyncRenderPerSec )
		{
			return webCore.CreateWebView( width, height, isTransparent, enableAsyncRendering, maxAsyncRenderPerSec );
		}

		#region IDisposable Members

		private void ReleaseCompositionTarget()
		{
			try { CompositionTarget.Rendering -= OnUpdate; }
			catch { }
		}

		public void Dispose()
		{
			Dispose( true );
			GC.SuppressFinalize( this );
		}

		private void Dispose( bool disposing )
		{
			if ( !disposed )
			{
				ReleaseCompositionTarget();
				disposed = true;
			}
		}

		~WebBrowserManager()
		{
			Dispose( false );
		}

		#endregion
	}
}